﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
	private static UIManager _instance;

	public enum panelLayerName
	{
		scene = 1,
		root = 2,
		primary = 3,
		secondary = 4,
		tips = 5,
		effect = 6,
		loading = 7

	};

	public UIDialog openDialog<T>(T dialogClass, UIDialog parent = null, bool setLast = false) where T:UIDialog
	{
		Object obj = Resources.Load(dialogClass.path(), typeof(GameObject));
		GameObject gameObj = GameObject.Instantiate(obj) as GameObject;
		if (gameObj == null)
			return null;

		var dClass = gameObj.AddComponent<T> ();

		if (parent == null) 
		{
			var pannel = this.panalLayer [dClass.panal ()];
			dClass.transform.parent = pannel.transform;
		} 
		else 
		{
			dClass.transform.parent = parent.transform;
		}
		if (setLast)
			dClass.transform.SetSiblingIndex(0);

		dClass.name = typeof(T).ToString();

		var rect = gameObj.GetComponent<RectTransform> ();
		rect.offsetMin = new Vector2 (0,0);
		rect.offsetMax = new Vector2 (0,0);

		rect.localScale = new Vector3 (1, 1, 1);

		return dClass;
	}

	public UIEffect addEffectByPath(string path, UIDialog uiDialog = null, float w = 0, float h = 0, bool setLast = false)
	{
		UIEffect uiEffect = (UIEffect)openDialog(new UIEffect (), uiDialog, setLast);
		uiEffect.setSize (w,h);
		uiEffect.addEffect (path);
		return uiEffect;
	}

	public void clearPannel(string pannelName)
	{
		var pannel = this.panalLayer [pannelName];
		pannel.clearAllDialog ();
	}

	public void closeDialogByName(string name)
	{
		foreach (var panal in panalLayer.Values) {
			panal.closeDialog (name);
		}
	}

	//-----	界面相关
	public Dictionary<string,UIPanal> panalLayer = new Dictionary<string,UIPanal>();

	public static UIManager getInstance()
	{
	    if (_instance == null)
	    {
			_instance = new UIManager ();
	        GlobalMessage.Instance.GameOverEvent = GameOver;
	    }
		return _instance;
	}

    private static void GameOver()
    {
		UIManager.getInstance ().openDialog (new UIGameover());
		UIManager.getInstance().clearPannel("scene");
		UIManager.getInstance().clearPannel("root");
    }
}
